package com.zhugang.week03;

import java.util.Stack;

/**
 * @program algorithms
 * @description: sortedStack
 * @author: chanzhugang
 * @create: 2022/06/04 17:04
 */
public class SortedStack {


    /**
     * 栈排序：
     * push：倒腾两个栈：一直让栈中的元素从大到小（栈顶元素最小）
     * pop、peek直接操作
     */
    Stack<Integer> stack = new Stack<>();
    Stack<Integer> tempStack = new Stack<>();

    public SortedStack() {

    }

    public void push(int val) {
        while (!stack.isEmpty() && stack.peek() < val) {
            // 当前元素放栈最底下（栈顶元素移到临时栈）
            tempStack.push(stack.pop());
        }
        stack.push(val);
        while (!tempStack.isEmpty()) {
            stack.push(tempStack.pop());
        }
    }

    public void pop() {
        if (!stack.empty()) {
            stack.pop();
        }
    }

    public int peek() {
        if (stack.isEmpty()) {
            return -1;
        }
        return stack.peek();
    }

    public boolean isEmpty() {
        return stack.isEmpty();
    }
}